import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
import { DataGrid, Form, Popup, ScrollView, SelectBox, TextBox, } from 'devextreme-react';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import { useState } from 'react';
import { intl, moneyFormatCol } from '@/utils';
import { useModel } from 'umi';
import { SimpleItem } from 'devextreme-react/form';
import { updateZL } from "../../service"
import "./index.less"
import notify from 'devextreme/ui/notify';
import BigNumber from 'bignumber.js';

export interface SizeProp {
    width?: number | string,
    height?: number | string,
}

const AgingaccountPopup: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;

    const { width, height, dataBillID, whereFrom } = props;

    const diaParams = useRef<AudDialogShowParams & any>();
    const refsForm = useRef<any>();

    const [formAllData, setFormAllData] = useState<any>({});
    const [diaParamsDataM, setDiaParamsDataM] = useState<any>([]);
    const [diaParamsDataY, setDiaParamsDataY] = useState<any>([]);
    const [visible, setVisible] = useState<boolean>(false);
    const [size, setSize] = useState<SizeProp>({ width, height });

    const ClearAway = () => {
        let tempFormAllData = {};
        diaParams.current?.args?.data.forEach((element: any) => {
            tempFormAllData = { ...tempFormAllData, [element.FieldName]: null }
        });
        setFormAllData(tempFormAllData);
    }


    const pushNumberData = (numStr: any, d: number = 2) => {
        // const cleanedValue = numStr?.replace(/[^0-9,-.]/g, '');
        // const numericValue = cleanedValue.replace(/,/g, '').replace(/(\..*)\./g, '$1') * 1;
        // if (!isNaN(numericValue)) {
        //     const num = new BigNumber(numericValue);
        //     const truncatedNumber = num.dp(d, BigNumber.ROUND_DOWN).toString();
        //     const formattedPrice = moneyFormatCol(truncatedNumber);
        //     return {
        //         success: true, truncatedNumber, formattedPrice
        //     }
        // }
        // return {
        //     success: false
        // }
        const num = new BigNumber(numStr);
        const truncatedNumber = num.dp(d, BigNumber.ROUND_DOWN).toString();
        const formattedPrice = moneyFormatCol(truncatedNumber);
        return {
            success: true, truncatedNumber, formattedPrice
        }
    }

    useImperativeHandle(ref, () => ({
        show: async (params: AudDialogShowParams) => {
            diaParams.current = params;
            let tempFormAllData = {};
            params?.args?.data.forEach((element: any) => {
                tempFormAllData = { ...tempFormAllData, [element.FieldName]: null }
            });
            const resM = params?.args?.data.filter((item: any) => {
                if (item.FieldName.includes('M') || item.FieldName === 'Y1') {
                    item.itemDispaly = false;
                    if (item.FieldName === 'Y1') {
                        item.itemDispaly = true;
                    }
                    return item;
                }
            });
            const resY = params?.args?.data.filter((item: any) => {
                return item.FieldName.includes('Y') && item.FieldName !== 'Y1';
            });
            setDiaParamsDataM(resM);
            setDiaParamsDataY(resY);
            if (resM.length || resY.length) {
                if (params?.args?.transformedData?.length) {
                    console.log(params?.args?.transformedData, '@@@ transformedData');
                    const tempObj = params?.args?.transformedData[0];
                    const tempObjKeyArr = Object.keys(tempObj);
                    if (tempObjKeyArr.length > 0) {
                        tempObjKeyArr.forEach((key) => {
                            console.log(key, '@@@ key');
                            if (tempObj[key]) {
                                const res = pushNumberData(`${tempObj[key]}`);
                                const temp_Number = Number(res.truncatedNumber || 0);
                                tempFormAllData[key] = temp_Number === 0 ? null : temp_Number;
                            }
                        });
                    }
                    setFormAllData(tempFormAllData);
                }
            } else {
                setFormAllData({});
            }

            setVisible(true);
        },
        close: () => { setVisible(false); setFormAllData({}); }
    }));

    const onOk = async () => {
        if (diaParams.current?.args?.data?.length === 0) {
            setVisible(false);
            return;
        }
        // 获取账龄区间年进行相加 根据金额数值 对比区间年度是否小于等于金额数值
        const filterKeys = Object.keys(formAllData).filter((item: any) => { return item.includes('Y') });
        // console.log(filterKeys, Object.keys(formAllData), '@@@');
        let totalY1_result = new BigNumber(0.00);
        for (const propName of filterKeys) {
            if (formAllData.hasOwnProperty(propName)) {
                totalY1_result = totalY1_result.plus(formAllData[propName] || 0);
            }
        }
        const resY1: any = pushNumberData(`${totalY1_result}` || '0');
        const str = diaParams.current?.args?.JE;
        if (resY1.formattedPrice === str) {
            if (diaParams.current?.args?.data.length > 0) {
                const resObj = { ...formAllData };
                // 遍历对象的属性
                const valData = Array.from(new Set(Object.values(resObj)));
                // console.log(resObj, valData, '@@@');
                if ((valData.length === 1 && (valData[0] === 0 || !valData[0])) || valData.length === 0) return notify("该账龄未修改，请分配账龄！", "warning", 2000);
                const r = await updateZL(whereFrom, {
                    dbname,
                    billID: dataBillID,
                    GUID: diaParams.current?.args?.GUID,
                    ...resObj
                })
                if (r) {
                    setVisible(false);
                    notify("账龄修改成功", "success", 2000);
                    diaParams.current?.okCallback();
                } else {
                    notify("账龄修改失败", "error", 2000);
                }
            } else {
                setVisible(false);
            }
        } else {
            notify("账龄段分配金额和总数不符！", "error", 2000)
        }
        return;


    }

    const onCancel = () => {
        setVisible(false);
        ClearAway();
        setFormAllData({});
    }

    const validateForm = (e: any) => {
        const updatedField: any = e.dataField;
        const newValue = e.value;

        console.log(e, '@@@');

        const res: any = pushNumberData(newValue || '0');
        if (updatedField.includes('M')) {
            const filterKeys1 = Object.keys(formAllData).filter((item: any) => { return item.includes('M') });
            let totalY1_result = new BigNumber(0.00);
            for (const propName of filterKeys1) {
                if (formAllData.hasOwnProperty(propName)) {
                    totalY1_result = totalY1_result.plus(formAllData[propName] || 0);
                }
            }
            const resY1: any = pushNumberData(`${totalY1_result}` || 0);

            console.log(resY1, '@@@');

            setFormAllData({
                ...formAllData,
                [updatedField]: e.value === 0 ? null : Number(res.truncatedNumber || 0),
                Y1: Number(resY1.truncatedNumber || 0) === 0 ? null : Number(resY1.truncatedNumber || 0),
            });
        } else {
            setFormAllData({
                ...formAllData,
                [updatedField]: e.value === 0 ? null : Number(res.truncatedNumber || 0),
            });
        }
    };

    // const validationRules = {
    //     changeNumber: [
    //         {
    //             type: "async",
    //             message: "小数点后只能输入两位！",
    //             validationCallback: async (item: any) => {
    //                 console.log(item, '@@@  小数点后只能输入两位！');

    //                 // const result = item.value === 'OK';
    //                 // if (result) {
    //                 //     return true;
    //                 // }
    //                 // return false;
    //             },
    //         },
    //     ]
    // }


    return (
        <>
            <Popup
                ref={ref}
                visible={visible}
                title={diaParams.current?.args?.title}
                minWidth={750}
                minHeight={600}
                {...props}
                {...size}
                // dragOutsideBoundary={true}
                resizeEnabled={true}
                onHiding={() => onCancel()}
                toolbarItems={[
                    {
                        cssClass: 'TextStyle',
                        toolbar: 'bottom',
                        location: "before",
                        text: diaParams.current?.args?.data?.length ? "" : '该科目没有分配账龄段',
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: '清空',
                            onClick: () => {
                                ClearAway();
                            }
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },

                ]}
                onResizeEnd={(e) => {
                    setSize({ width: e.width, height: e.height });
                }}
            >
                <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
                    <div style={{ width: '100%', height: '20%', display: 'flex', justifyContent: 'center' }}>
                        <div style={{ width: '80%', height: '20%', }}>
                            <Form colCount={2}  >
                                <SimpleItem
                                    label={{ text: '科目编号' }}
                                    editorType='dxTextBox'
                                    editorOptions={{
                                        valueChangeEvent: 'keyup',
                                        readOnly: true,
                                        showClearButton: true,
                                        value: diaParams.current?.args?.KMBH
                                    }}
                                />
                                <SimpleItem
                                    label={{ text: '科目名称' }}
                                    editorType='dxTextBox'
                                    editorOptions={{
                                        valueChangeEvent: 'keyup',
                                        readOnly: true,
                                        showClearButton: true,
                                        value: diaParams.current?.args?.KMMC
                                    }}
                                />

                                <SimpleItem
                                    label={{ text: diaParams.current?.args?.name }}
                                    editorType='dxTextBox'
                                    editorOptions={{
                                        valueChangeEvent: 'keyup',
                                        readOnly: true,
                                        showClearButton: true,
                                        value: diaParams.current?.args?.JE ? diaParams.current?.args?.JE : '0.00'
                                    }}
                                />
                                <SimpleItem
                                    label={{ text: '辅助账名称' }}
                                    editorType='dxTextBox'
                                    editorOptions={{
                                        valueChangeEvent: 'keyup',
                                        readOnly: true,
                                        showClearButton: true,
                                        value: diaParams.current?.args?.FZZMC
                                    }}
                                />
                            </Form>
                        </div>
                    </div>
                    <div style={{ width: '100%', height: '80%', display: 'flex', justifyContent: 'center' }}>
                        {useMemo(() => {
                            let SimpleItemA: any = '';
                            let SimpleItemB: any = '';
                            if (diaParamsDataM.length) {
                                SimpleItemA = diaParamsDataM.map((item: any) => <SimpleItem
                                    dataField={item.FieldName}
                                    label={{ text: item.Caption }}
                                    editorType='dxNumberBox'
                                    editorOptions={{
                                        readOnly: diaParamsDataM.length > 1 && item.itemDispaly,
                                        format: "#,##0.00;-#,##0.00",
                                    }}
                                />);
                            }
                            if (diaParamsDataY.length) {
                                SimpleItemB = diaParamsDataY.map((item: any) => <SimpleItem
                                    dataField={item.FieldName}
                                    editorType='dxNumberBox'
                                    label={{ text: item.Caption }}
                                    editorOptions={{
                                        format: "#,##0.00;-#,##0.00",
                                    }}
                                />
                                );
                            }
                            // debugger;
                            return <ScrollView width='100%' height='100%'>
                                <div style={{ display: 'flex', justifyContent: 'center' }}>
                                    <Form
                                        width='80%'
                                        ref={refsForm}
                                        // colCount={2}
                                        formData={formAllData}
                                        labelLocation={"left"}
                                        labelMode={"outside"}
                                        // focusStateEnabled={true}
                                        showColonAfterLabel={true}
                                        alignItemLabels={true}
                                        onFieldDataChanged={validateForm}
                                    >
                                        {SimpleItemA}
                                        {SimpleItemB}
                                    </Form>
                                </div>
                            </ScrollView>
                        }, [diaParamsDataM, diaParamsDataY, formAllData])}
                    </div>
                </div>
            </Popup >
        </>
    );
});


export default React.memo(AgingaccountPopup);